import * as React from 'react';
import * as ReactDOM from 'react-dom/client';
import LiteFlowEditor from './index.tsx';

class LiteFlowEditorElement extends HTMLElement {
  private root: ReactDOM.Root | null = null;
  private mountPoint: HTMLDivElement | null = null;

  connectedCallback() {
    try {
      this.mountPoint = document.createElement('div');
      this.mountPoint.style.width = '100%';
      this.mountPoint.style.height = '100%';
      this.appendChild(this.mountPoint);

      this.mountPoint.addEventListener('liteflow:save', (event) => {
        this.dispatchEvent(new CustomEvent('liteflow:save', {
          detail: (event as CustomEvent).detail
        }));
      });

      this.root = ReactDOM.createRoot(this.mountPoint);
      this.updateComponent();
    } catch (error) {
      console.error('Error in connectedCallback:', error);
    }
  }

  disconnectedCallback() {
    try {
      if (this.mountPoint) {
        this.mountPoint.removeEventListener('liteflow:save', this.handleSave);
        this.removeChild(this.mountPoint);
        this.mountPoint = null;
      }
      if (this.root) {
        this.root.unmount();
      }
    } catch (error) {
      console.error('Error in disconnectedCallback:', error);
    }
  }

  private updateComponent() {
    if (!this.root) return;

    try {
      const data = this.getAttribute('data');
      console.log('Current data:', data); // 调试用

      const props = {
        data: data ? JSON.parse(data) : {},
        onReady: (graph: any) => {
          console.log('Graph ready called with:', graph); // 调试用
          this.dispatchEvent(new CustomEvent('ready', { detail: graph }));
        }
      };

      this.root.render(React.createElement(LiteFlowEditor, props));
    } catch (error) {
      console.error('Error in updateComponent:', error);
    }
  }

  static get observedAttributes() {
    return ['data'];
  }

  attributeChangedCallback(name: string, oldValue: string, newValue: string) {
    console.log(`Attribute ${name} changed from ${oldValue} to ${newValue}`); // 调试用
    this.updateComponent();
  }
}

customElements.define('lite-flow-editor', LiteFlowEditorElement); 